<template>
    <div style="position: relative;">
        <slot></slot>
        <a-upload
            :custom-request="httpRequest"
            :show-upload-list="false"
            accept="image/jpg,image/jpeg,image/png,image/bmp,image/gif"
            action=""
            class="avatar-uploader"
            list-type="picture-card"
        >
            <img v-if="url && !loading" :src="url" style="width: 86px;height: 86px"/>
            <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'"/>
                <div class="ant-upload-text">
                    {{ loading ? '上传中' : '上传' }}
                </div>
            </div>
        </a-upload>
        <span v-if="tips"
              style="color: red;line-height: 14px;position: absolute;left: 0;bottom: 0;font-size: 12px">{{
                tips
            }}</span>
    </div>
</template>

<script>
import {uploadImage} from '@/api/api'

export default {
    name: 'Index',
    props: {
        url: {
            type: String,
            default: ''
        },
        tips: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            loading: false
        }
    },
    methods: {
        /**
         *  上传图片
         */
        // 新增上传图片
        async httpRequest(file) {
            if (file.file.size > 500 * 1024) {
                this.$message.error('上传大小不能超过500kb');
                return
            }
            const list = ['image/jpg', 'image/png', 'image/jpeg']
            if (list.indexOf(file.file.type.toLowerCase()) === -1) return this.$message.error('上传格式不正确');
            this.loading = true
            const formData = new FormData()
            formData.append('file', file.file)
            const res = await uploadImage(formData)
            console.log(res)
            this.$emit('change-url', res.imgUrl)
            this.loading = false
            return false
        }
    }
}
</script>

<style lang='scss' scoped>

</style>
